package bio_nio_aio.bio.com_base.netcode;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;


//客户端给服务端发送信息，服务端输出此信息到控制台上
public class TestTcp1 {
	// 这里是使用 TCP 来实现的
	// 客户端
	@Test
	public void client() {

		Socket socket = null;
		OutputStream os = null;
		try {
			socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
			os = socket.getOutputStream();
			os.write("我是客户端请多多关照".getBytes());

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null)
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (socket != null)
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

	}

	// 服务端
	@Test
	public void server() throws IOException {

		ServerSocket ss = new ServerSocket(9090);
		//等待请求（默认只是开启一次）
		Socket socket = ss.accept();
		InputStream is = socket.getInputStream();
		byte[] b = new byte[1024];
		int len;
		while ((len = is.read(b)) != -1) {// 文件的尾端都有一个 -1
			System.out.println(new String(b, 0, len));
		}

		is.close();
		socket.close();
		ss.close();
	}

}
